<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-operator" v-action:create>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="所属村">
                <a-select :allowClear="true" v-model="queryParam.village_id" placeholder="请选择村庄" default-value="0">
                  <a-select-option v-for="(item, index) in villList" :key="index" :value="item.village_id">
                    {{ item.village_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="7" :sm="24">
              <a-form-item label="标题">
                <a-input :allowClear="true" v-model="queryParam.user_name" placeholder="请输入标题"/>
              </a-form-item>
            </a-col> -->
            <a-col :md="4" :sm="24">
              <a-form-item label="答题人">
                <a-input :allowClear="true" v-model="queryParam.user_name" placeholder="请输入答题人"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="结算状态">
                <a-select :allowClear="true" v-model="queryParam.settle_status" placeholder="请选择结算状态">
                  <a-select-option value="">
                    全部
                  </a-select-option>
                  <a-select-option :value="0">
                    未结算
                  </a-select-option>
                  <a-select-option :value="1">
                    已结算
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="settle_status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span style="text-align: center;" slot="action" slot-scope="text, record">
          <template>
            <!-- <a v-if="record.status == 1" @click="handleChangeStatus(record)" v-action:change_status>撤回</a>
            <a-divider v-if="record.status == 1" type="vertical"/> -->
            <a @click="handleSub(record)" v-action:answer_info>详情</a>
            <!-- <a-divider v-if="record.settle_status == 0" type="vertical"/>
            <a @click="handleChangeStatus(record)" v-if="record.settle_status == 0" v-action:edit>结算</a> -->
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
        :serveList="serveList"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { serviceList, serviceContentCreate, serviceContentEdit, serviceContentDel, serviceContentChangeStatus } from '@/api'
import CreateForm from './modules/CreateAnswerLogForm'
import { answerList, answerInfo } from '@/api/exam'
import { villageList } from '@/api/distribution'
const statusMap = {
  0: {
    status: 'default',
    text: '未结算'
  },
  1: {
    status: 'success',
    text: '已结算'
  }
}

const columns = [
  {
    title: '问卷标题',
    dataIndex: 'survey_title',
    align: 'center'
  },
  {
    title: '答题人',
    dataIndex: 'fullname',
    align: 'center'
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    align: 'center'
  },
  {
    title: '所属村',
    dataIndex: 'village_name',
    align: 'center',
    scopedSlots: { customRender: 'village_name' }
  },
  {
    title: '回答时间',
    dataIndex: 'created_at',
    align: 'center',
    scopedSlots: { customRender: 'created_at' }
  },
  {
    title: '答题结果',
    dataIndex: 'right_num',
    align: 'center',
    scopedSlots: { customRender: 'right_num' }
  },
  {
    title: '得分',
    dataIndex: 'score',
    align: 'center',
    scopedSlots: { customRender: 'score' }
  },
  {
    title: '结算状态',
    dataIndex: 'settle_status',
    align: 'center',
    scopedSlots: { customRender: 'settle_status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: null,
      isPost: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        'fullname': '',
        'score': '',
        'paper': '',
        'mobile': '',
        'village_name': '',
        'right_num': '',
        'total_num': '',
        'end_time': '',
        'detailed_rules': '',
        'times': ''
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        if (!this.isPost) return
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await answerList({
          ...params,
          ...this.queryParam
        })
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      serveList: [],
      selectedRowKeys: [],
      selectedRows: [],
      villList: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.queryParam['survey_id'] = this.$router.app._route.query.id
    this.isPost = true
    this.$nextTick(() => {
      this.$refs.table.refresh()
    })
    serviceList().then(res => {
      this.serveList = res.list
    })
    villageList().then((res) => {
      this.villList = res.list
    })
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (values.id > 0) {
            serviceContentEdit({ ...values, image: values?.image?.[0].url })
              .then(res => success(res, '修改成功'))
              .finally(final)
          } else {
            serviceContentCreate({ ...values, image: values?.image?.[0].url })
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record) {
      this.openModal(serviceContentChangeStatus, record, '撤回')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该内容吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method({ id: record.id })
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      this.visible = true
      this.okHidden = true
      answerInfo({ id: record.id }).then((res) => {
         this.mdl = res
      })
    },
    async handleRemove (record) {
      this.openModal(serviceContentDel, record, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      const id = this.queryParam['survey_id']
      this.queryParam = {
        survey_id: id
      }
    }
  }
}
</script>
